package com.base.openeye.glide

import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import okhttp3.OkHttpClient
import java.io.InputStream
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.GlideBuilder
import okhttp3.logging.HttpLoggingInterceptor


/**
 * @author Administrator
 * @date 2018/2/12 0012 下午 3:16
 * GitHub：
 * email：
 * description：
 */
@GlideModule
class MyAppGlideModule : AppGlideModule() {

    private val okHttpClient = OkHttpClient
            .Builder()
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
            .build()

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        //手动分配缓存  缓存4屏图片，默认是2
        val calculator = MemorySizeCalculator.Builder(context)
                .setMemoryCacheScreens(4f)
                .build()

        //将Glide图片缓存到SD卡
        //builder.setDiskCache(new ExternalCacheDiskCacheFactory(context));

        builder.setMemoryCache(LruResourceCache(calculator.memoryCacheSize.toLong()))
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)

        //更换网络请求为OkHttp
        registry.replace(
                GlideUrl::class.java,
                InputStream::class.java,
                OkHttpUrlLoader.Factory(okHttpClient)
        )
    }

    override fun isManifestParsingEnabled() = false
}